/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MyThread;


import MyLib.Comvar;
import MyLib.MyFile;
import Object.Chunk;
import Object.Torrent;
import XML.DOMUtil;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;

/**
 *
 * @author QuangHau
 */
public class CreateTorrenFile extends Thread {

    File source;
    File destination;
    JTextArea textArea;

    public CreateTorrenFile(File SourceFile, File SestinationFile, JTextArea TextArea) {
        source = SourceFile;
        destination = SestinationFile;
        textArea = TextArea;
    }

    public void run() {
        Comvar.writeLog(1, CreateTorrenFile.class.getName(), "BEGIN CREATE TORRENFILE OF " + source.getName());
        ObjectOutputStream outStream;
        try {
            outStream = new ObjectOutputStream(
                    new FileOutputStream(destination.getAbsolutePath()));
            Date today = new Date(System.currentTimeMillis());
            String folder = InetAddress.getLocalHost().getHostName() + Long.toString(today.getTime());
            outStream.writeObject(folder);//id
            outStream.writeObject(source.getName());//name
            outStream.writeObject((int) source.length());//size
            File file = new File("Data\\" + folder);
            if (!file.exists()) {
                file.mkdirs();
            }
            ArrayList<Chunk> listChunk = readAndFragment(source.getAbsolutePath(), folder);
            outStream.writeObject(listChunk);
            outStream.close();
            
            //Cap nhat data
            textArea.append("Update database...\n");
            updateData( new Torrent(folder, source.getName(), (int) source.length(), listChunk), listChunk);
        } catch (IOException ex) {
            Logger.getLogger(Torrent.class.getName()).log(Level.SEVERE, null, ex);
        }
        textArea.append("Successful!");
        textArea.setCaretPosition(textArea.getDocument().getLength());
        Comvar.writeLog(1, CreateTorrenFile.class.getName(), "END CREATE TORRENFILE OF " + source.getName());
    }

    private ArrayList<Chunk> readAndFragment(String SourceFileName, String destinationFile) {
        int CHUNK_SIZE = 524288;
        File willBeRead = new java.io.File(SourceFileName);
        int FILE_SIZE = (int) willBeRead.length();
        ArrayList<Chunk> chunkList = new ArrayList<Chunk>();
        int NUMBER_OF_CHUNKS = 0;
        byte[] temporary = null;

        try {
            InputStream inStream = null;
            int totalBytesRead = 0;

            try {
                inStream = new BufferedInputStream(new FileInputStream(willBeRead));

                while (totalBytesRead < FILE_SIZE) {
                    Chunk chunkItem = new Chunk();
                    String PART_NAME = "Data\\" + destinationFile + "\\" + NUMBER_OF_CHUNKS + ".chunk";
                    chunkItem.setId(Integer.toString(NUMBER_OF_CHUNKS));

                    int bytesRemaining = FILE_SIZE - totalBytesRead;
                    if (bytesRemaining < CHUNK_SIZE) // Remaining Data Part is Smaller Than CHUNK_SIZE
                    // CHUNK_SIZE is assigned to remain volume
                    {
                        CHUNK_SIZE = bytesRemaining;
                    }
                    temporary = new byte[CHUNK_SIZE]; //Temporary Byte Array
                    int bytesRead = inStream.read(temporary, 0, CHUNK_SIZE);

                    textArea.append("Write chunk " + NUMBER_OF_CHUNKS + "\n");
                    textArea.setCaretPosition(textArea.getDocument().getLength());
                    
                     MyFile.write(temporary, PART_NAME);
                    chunkItem.setHash(MyFile.generateBufferedHash(temporary));
                    chunkList.add(chunkItem);
                    if (bytesRead > 0) // If bytes read is not empty
                    {
                        totalBytesRead += bytesRead;
                        NUMBER_OF_CHUNKS++;
                    }
                }

            } finally {
                inStream.close();
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return chunkList;
    }
    
     private void updateData(Torrent torrenFile, ArrayList<Chunk> listChunk) {
         for(int i=0; i< listChunk.size(); i++)
         {
             DOMUtil.insertChunk(torrenFile, listChunk.get(i).getId());
         }
     }
    
}
